package com.buaa.divinationmaster.manager;

import android.content.Context;

import com.buaa.divinationmaster.core.database.DivinationDatabase;
import com.buaa.divinationmaster.core.database.entities.DivinationHistory;
// 使用完整包名避免命名冲突
import com.buaa.divinationmaster.model.DivinationRecord;
import com.buaa.divinationmaster.model.TarotCard;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 数据库管理器
 * 提供统一的数据访问接口
 */
public class DatabaseManager {
    
    private static DatabaseManager instance;
    private DivinationDatabase database;
    private ExecutorService executor;
    
    private DatabaseManager(Context context) {
        database = DivinationDatabase.getInstance(context);
        executor = Executors.newFixedThreadPool(4);
    }
    
    public static synchronized DatabaseManager getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseManager(context.getApplicationContext());
        }
        return instance;
    }
    
    /**
     * 保存占卜记录
     */
    public void saveRecord(DivinationRecord record, OnDataCallback<Long> callback) {
        executor.execute(() -> {
            try {
                DivinationHistory entity = new DivinationHistory();
                entity.type = record.getType();
                entity.question = record.getQuestion();
                entity.resultData = record.getResultData();
                entity.interpretation = record.getInterpretation();
                entity.timestamp = record.getTimestamp();
                entity.isFavorite = record.isFavorite();
                entity.tags = record.getTags();
                
                long id = database.divinationHistoryDao().insert(entity);
                
                if (callback != null) {
                    callback.onSuccess(id);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 获取所有占卜记录
     */
    public void getAllRecords(OnDataCallback<List<DivinationRecord>> callback) {
        executor.execute(() -> {
            try {
                List<DivinationHistory> entities = database.divinationHistoryDao().getAllHistorySync();
                List<DivinationRecord> records = convertToRecords(entities);
                
                if (callback != null) {
                    callback.onSuccess(records);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 分页获取占卜记录
     */
    public void getRecordsPaged(int limit, int offset, OnDataCallback<List<DivinationRecord>> callback) {
        executor.execute(() -> {
            try {
                List<DivinationHistory> entities = database.divinationHistoryDao().getHistoryPaged(limit, offset);
                List<DivinationRecord> records = convertToRecords(entities);
                
                if (callback != null) {
                    callback.onSuccess(records);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 搜索占卜记录
     */
    public void searchRecords(String keyword, OnDataCallback<List<DivinationRecord>> callback) {
        executor.execute(() -> {
            try {
                List<DivinationHistory> entities = database.divinationHistoryDao().searchHistorySync(keyword);
                List<DivinationRecord> records = convertToRecords(entities);
                
                if (callback != null) {
                    callback.onSuccess(records);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 删除占卜记录
     */
    public void deleteRecord(long id, OnDataCallback<Void> callback) {
        executor.execute(() -> {
            try {
                DivinationHistory entity = database.divinationHistoryDao().getHistoryById(id);
                if (entity != null) {
                    database.divinationHistoryDao().delete(entity);
                }
                
                if (callback != null) {
                    callback.onSuccess(null);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 获取记录数量
     */
    public void getRecordCount(OnDataCallback<Integer> callback) {
        executor.execute(() -> {
            try {
                int count = database.divinationHistoryDao().getHistoryCount();
                
                if (callback != null) {
                    callback.onSuccess(count);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 清除所有历史记录
     */
    public void clearAllRecords(OnDataCallback<Void> callback) {
        executor.execute(() -> {
            try {
                database.divinationHistoryDao().deleteAll();
                
                if (callback != null) {
                    callback.onSuccess(null);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    /**
     * 获取所有塔罗牌
     */
    public void getAllTarotCards(OnDataCallback<List<TarotCard>> callback) {
        executor.execute(() -> {
            try {
                List<com.buaa.divinationmaster.core.database.entities.TarotCard> entities = database.tarotCardDao().getAllCardsSync();
                List<TarotCard> cards = convertToTarotCards(entities);
                
                if (callback != null) {
                    callback.onSuccess(cards);
                }
            } catch (Exception e) {
                if (callback != null) {
                    callback.onError(e);
                }
            }
        });
    }
    
    // 转换方法
    private List<DivinationRecord> convertToRecords(List<DivinationHistory> entities) {
        List<DivinationRecord> records = new ArrayList<>();
        for (DivinationHistory entity : entities) {
            DivinationRecord record = new DivinationRecord();
            record.setId(entity.id);
            record.setType(entity.type);
            record.setQuestion(entity.question);
            record.setResultData(entity.resultData);
            record.setInterpretation(entity.interpretation);
            record.setTimestamp(entity.timestamp);
            record.setFavorite(entity.isFavorite);
            record.setTags(entity.tags);
            records.add(record);
        }
        return records;
    }
    
    private List<TarotCard> convertToTarotCards(List<com.buaa.divinationmaster.core.database.entities.TarotCard> entities) {
        List<TarotCard> cards = new ArrayList<>();
        for (com.buaa.divinationmaster.core.database.entities.TarotCard entity : entities) {
            TarotCard card = new TarotCard();
            card.setId(entity.id);
            card.setNameZh(entity.nameZh);
            card.setNameEn(entity.nameEn);
            card.setType("major".equals(entity.type) ? TarotCard.CardType.MAJOR_ARCANA : TarotCard.CardType.MINOR_ARCANA);
            
            // 设置花色
            if (entity.suit != null) {
                switch (entity.suit) {
                    case "wands": card.setSuit(TarotCard.Suit.WANDS); break;
                    case "cups": card.setSuit(TarotCard.Suit.CUPS); break;
                    case "swords": card.setSuit(TarotCard.Suit.SWORDS); break;
                    case "pentacles": card.setSuit(TarotCard.Suit.PENTACLES); break;
                    default: card.setSuit(TarotCard.Suit.NONE); break;
                }
            }
            
            card.setNumber(entity.number);
            card.setImagePath(entity.imagePath);
            card.setUprightKeywords(entity.uprightKeywords);
            card.setUprightMeaning(entity.uprightMeaning);
            card.setReversedKeywords(entity.reversedKeywords);
            card.setReversedMeaning(entity.reversedMeaning);
            
            // 设置元素
            if (entity.element != null) {
                switch (entity.element) {
                    case "fire": card.setElement(TarotCard.Element.FIRE); break;
                    case "water": card.setElement(TarotCard.Element.WATER); break;
                    case "air": card.setElement(TarotCard.Element.AIR); break;
                    case "earth": card.setElement(TarotCard.Element.EARTH); break;
                }
            }
            
            cards.add(card);
        }
        return cards;
    }
    
    /**
     * 数据回调接口
     */
    public interface OnDataCallback<T> {
        void onSuccess(T data);
        void onError(Exception error);
    }
}
